<template>
  <Dialog v-model="dialogVisibleForm" title="合并">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formLabels"
      label-width="120px"
    >
      <el-row>
        <el-col :span="10">
          <el-form-item label="待合并模版" prop="label">
            <el-input
              v-model="formData.tamplate.label"
              placeholder="请选择模版"
              @click="openTemplate(1)"
            />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="标签名称" prop="labelid">
            <el-tree-select
              v-model="formData.labelid"
              :data="tamplateData"
              check-strictly
              :render-after-expand="false"
              style="width: 240px"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="待合并模版" prop="label2">
            <el-input
              v-model="formData.tamplate2.label"
              placeholder="请选择模版"
              @click="openTemplate(2)"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="标签名称" prop="labelid2">
            <el-tree-select
              v-model="formData.labelid2"
              :data="tamplateData2"
              check-strictly
              :render-after-expand="false"
              style="width: 240px"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="模版标识" prop="newtamplateid">
            <el-input v-model="formData.newtamplateid"
          /></el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="模版名称" prop="newtamplatename">
            <el-input v-model="formData.newtamplatename" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisibleForm = false">取 消</el-button>
    </template>
  </Dialog>
  <Dialog v-model="dialogVisible" title="合并模版" width="800px" max-height="600px" @close="close">
    <el-check-tag
      class="m-5px text-15px"
      v-for="(item, index) in keywords"
      :key="item.id"
      type="info"
      round
      size="large"
      :checked="item.checked"
      @change="onchange(index)"
    >
      {{ item.labelname }}
    </el-check-tag>

    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitFormTamplate"
        >确 定</el-button
      >
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <!-- 标签合并 把formData 传过去 从而实现双向绑定 -->
  <!-- <Tag ref="tagRef" v-model="formData" /> -->
</template>
<script lang="ts" setup>
import { number } from 'vue-types'

import * as BiaoqianApi from '@/api/system/biaoqian'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisibleForm = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用

const tamplateData = ref([])
const tamplateData2 = ref([])
const index = ref(0)
const keywords = ref([]) // 关键字数组
const dialogVisible = ref(false) // 弹窗的是否展示
const isFlag = ref(false)

// 测试标签合并页面树形结构展示及选择
const formData = ref({
  tamplate: {
    label: '',
    value: ''
  },
  labelname: '',
  labelid: '',
  tamplate2: {
    label: '',
    value: ''
  },
  labelname2: '',
  labelid2: '',
  newtamplateid: '',
  fatherid: number,
  newtamplatename: ''
})
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (!formData.value.tamplate2.value) {
    callback(new Error('Please input the password again'))
  } else {
    callback()
  }
}
// defineOptions<{ data: string }>()
// 设置表单必填项验证
const formLabels = reactive({
  type: [{ required: true, message: '请假类型不能为空', trigger: 'change' }],
  // label: [{ required: true, message: '待合并模版名称不能为空', trigger: 'blue' }],
  labelid: [{ required: true, message: '标签名称不能为空', trigger: 'change' }],
  // label2: [{ required: true, message: '待合并模版名称不能为空', trigger: 'change' }],
  label2: [{ validator: validatePass2, trigger: 'change' }],
  labelid2: [{ required: true, message: '标签名称不能为空', trigger: 'change' }],
  newtamplateid: [{ required: true, message: '模版标识不能为空', trigger: 'change' }],
  newtamplatename: [{ required: true, message: '模版名称不能为空', trigger: 'change' }]
})

const openTemplate = async (ind: number) => {
  index.value = ind
  const data = await BiaoqianApi.selectTreeName()

  keywords.value = data.map((item) => {
    return { ...item, checked: false }
  })
  dialogVisible.value = true
  // 当点击模版选择框时(标签值需要清空)
  if (ind == 1) {
    formData.value.labelname = ''
    formData.value.labelid = ''
  } else {
    formData.value.labelname2 = ''
    formData.value.labelid2 = ''
  }
}
//  打开模版选择模版时的点击事件
const onchange = (value) => {
  if (isFlag.value) keywords.value.forEach((it) => (it.checked = false))
  keywords.value[value].checked = !keywords.value[value].checked
}
let listBiaoqianApiParams = ref({})

// 通过标识获取标签名称
const getTreeList = async (id) => {
  if (id == 1) {
    if (!formData.value.tamplate.value) return message.info('请选择模版')
    listBiaoqianApiParams.value = { nameList: formData.value.tamplate.value, labelname: '' }
    tamplateData.value = await BiaoqianApi.getBiaoQianTree(listBiaoqianApiParams.value)
    // dialogVisibleMerge.value = true
    console.log('-----------标签树形结构为-----------', tamplateData.value)
  } else {
    if (!formData.value.tamplate2.value) return message.info('请选择模版')
    listBiaoqianApiParams.value = { nameList: formData.value.tamplate2.value, labelname: '' }
    tamplateData2.value = await BiaoqianApi.getBiaoQianTree(listBiaoqianApiParams.value)
    // dialogVisibleMerge2.value = true
    // console.log(treeData2.value, '-----------标签树形结构为-----------')
  }
}
const formRef = ref() // 表单 Ref
/** 打开弹窗 */
const open = async () => {
  resetForm()
  dialogVisibleForm.value = true
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const submitForm = async () => {
  // 表单校验
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 创建 FormData 对象
  const formData2 = new FormData()
  formData2.append('tamplateY', formData.value.tamplate.value)
  formData2.append('tamplateE', formData.value.tamplate2.value)
  formData2.append('labelY', formData.value.labelid)
  formData2.append('labelE', formData.value.labelid2)
  formData2.append('newtamplateid', formData.value.newtamplateid)
  formData2.append('newtamplatename', formData.value.newtamplatename)
  console.log(formData2.get('tamplateY'), '-------------formData2的值-----------')
  await BiaoqianApi.mergeLabel(formData2 as unknown as BiaoqianApi.MergeLabel)
  dialogVisibleForm.value = false
  message.success(t('common.createSuccess'))
}
/** 选择模版的提交 */
const submitFormTamplate = async () => {
  listBiaoqianApiParams.nameList = keywords.value
    .filter((item) => item.checked)
    .map((it) => it.tamplateid)
    .join(';')

  // 触发父组件方法 再由父组件触发 子组件标签树形结构 方法 并传递参数
  // 关闭弹框
  dialogVisible.value = false

  if (index.value == 1) {
    formData.value.tamplate = {
      label: keywords.value.find((item) => item.checked).labelname || '',
      value: keywords.value.find((item) => item.checked).tamplateid || ''
    }
    getTreeList(index.value)
  } else if (index.value == 2) {
    formData.value.tamplate2 = {
      label: keywords.value.find((item) => item.checked).labelname || '',
      value: keywords.value.find((item) => item.checked).tamplateid || ''
    }
    getTreeList(index.value)
  }

  console.log(formData.value, 'formData的值')
  // console.log(api)
}
/**重置表单 */
const resetForm = () => {
  formData.value = {
    tamplate: {
      label: '',
      value: ''
    },
    labelname: '',
    labelid: '',
    tamplate2: {
      label: '',
      value: ''
    },
    labelname2: '',
    labelid2: '',
    newtamplateid: '',
    fatherid: number,
    newtamplatename: ''
  }
}
/** 关键字展示 */
const openKeywords = ref()
</script>
